const http = require('http');
const querystring = require('querystring');
const { apiUrl, apiPort, requestUrl } = require('./../config');
const { apiToken } = require('./common');

const getUrl = (key = '') => {
    return typeof requestUrl[key] != 'undefined' ? requestUrl[key] : '';
}

const get = (url = '', param = {}) => {
    return new Promise((resolve, reject) => {
        let options = {
            host: apiUrl,
            port: apiPort,
            path: getUrl(url),
        };
        let params = { ...param, ...apiToken() }
        let query = [];
        for (let k in params) {
            query.push(`${k}=${params[k]}`);
        }
        if (query.length > 0) {
            if (options.path.indexOf('?') == -1) {
                options.path += '?';
            } else {
                options.path += '&';
            }
            options.path += query.join('&');
        }
        let req = http.get(options, res => {
            res.setEncoding('utf8');
            let strem = '';
            res.on('data', function (data) {
                strem = strem + data;
            });
            res.on('end', () => {
                resolve(strem)
            });
        })
        req.on('error', function (e) {
            console.log('problem with request: ' + e.message);
            reject(e)
        });
    })
}

const post = (url = '', params = {}, config = {}, urlAdd = {}) => {
    return new Promise((resolve, reject) => {
        let pathUrl=getUrl(url);
        let keys=Object.keys(urlAdd);
        let pathAdds=[];
        for(let k of keys){
            pathAdds.push(k+'='+urlAdd[k]);
        }
        if(pathAdds.length>0){
            pathUrl+=pathUrl.indexOf('?')!=-1?'&'+pathAdds.join('&'):'?'+pathAdds.join('&');
        }
        let request_data = querystring.stringify({ ...params, ...apiToken() });
        let options = {
            host: apiUrl,
            port: apiPort,
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(request_data)
            },
            path: pathUrl,
            ...config
        };
        let req = http.request(options, res => {
            res.setEncoding('utf8');
            let strem = '';
            res.on('data', function (data) {
                strem = strem + data;
            });
            res.on('end', () => {
                resolve(strem)

            });
        })
        req.on('error', function (e) {
            console.log('problem with request: ' + e.message);
            reject(e)
        });
        req.write(request_data);
        req.end();
    })
}
module.exports = {
    get,
    post
}
